package com.wuye.web.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wuye.utils.Result;
import com.wuye.web.system.entity.SaveRoleIdsByUserIdParam;
import com.wuye.web.system.entity.SysRole;
import com.wuye.web.system.entity.SysUser;
import com.wuye.web.system.entity.SysUserParam;
import com.wuye.web.system.service.ISysRoleService;
import com.wuye.web.system.service.ISysUserRoleService;
import com.wuye.web.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author 孤筏
 * @since 2023-07-21
 */
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户管理")
public class SysUserController {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysRoleService roleService;
    @Resource
    private ISysUserRoleService userRoleService;

    @ApiOperation("新增用户")
    @PostMapping
    public Result addUser(@RequestBody SysUser user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        boolean save = userService.save(user);
        if (save){
            return Result.success();
        }
        return Result.error(500,"新增失败");
    }

    @ApiOperation("编辑用户")
    @PutMapping
    public Result editUser(@RequestBody SysUser user){
        boolean update = userService.updateById(user);
        if (update){
            return Result.success();
        }
        return Result.error(500,"修改失败");
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{userId}")
    public Result deleteUser(@PathVariable("userId") Integer userId){
        boolean delete = userService.removeById(userId);
        if (delete){
            return Result.success();
        }
        return Result.error(500,"删除失败");
    }

    @ApiOperation("展示用户信息")
    @GetMapping("/list")
    public Result listSysUser(SysUserParam sysUserParam){
        IPage<SysUser> page = userService.list(sysUserParam);
        return Result.success(page);
    }

    @ApiOperation("查询所有角色并选中当前用户所拥有的角色")
    @GetMapping("checkRoles/{userId}")
    public Result checkRoles(@PathVariable("userId") Integer userId){
        List<SysRole> roleList = roleService.checkRoles(userId);
        return Result.success(roleList);
    }

    @ApiOperation("保存用户所拥有的角色信息")
    @PutMapping("/saveRoleIdsByUserId")
    public Result saveRoleIdsByUserId(@RequestBody SaveRoleIdsByUserIdParam param){
        boolean save = userRoleService.saveRoleIdsByUserId(param);
        if (save){
            return Result.success();
        }
        return Result.error(500,"保存角色信息失败");
    }

}
